package com.corn.flink.lesson6;

import com.corn.flink.lesson4.Event;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

/**
 * @author JimWu
 * @date 2023/4/17 14:08
 **/
public class FlinkOutsidePutStreamDemo {

    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        DataStreamSource<Event> ds = env.fromElements(
                new Event("add", 1000),
                new Event("delete", 2000),
                new Event("update", 3000),
                new Event("select", 5000),
                new Event("add", 6000),
                new Event("delete", 7000),
                new Event("select", 8000),
                new Event("select", 9000),
                new Event("select", 10000),
                new Event("select", 11000)
        );

        // 定义侧数据流
        OutputTag<Event> addEvent = new OutputTag<Event>("addEvent") {
        };
        OutputTag<Event> selectEvent = new OutputTag<Event>("selectEvent") {
        };

        SingleOutputStreamOperator<Event> processDs = ds.process(new ProcessFunction<Event, Event>() {
            @Override
            public void processElement(Event value, Context ctx, Collector<Event> out) throws Exception {
                if (value.type.equals("add")) {
                    ctx.output(addEvent, value);
                } else if (value.type.equals("select")) {
                    ctx.output(selectEvent, value);
                } else {
                    out.collect(value);
                }
            }
        });
        processDs.print("otherEvent");

        // 获取测输出流数据
        processDs.getSideOutput(addEvent).print("addEvent");
        processDs.getSideOutput(selectEvent).print("selectEvent");
        env.execute();
    }
}
